import javax.swing.tree.TreeNode;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ws
 * Date: 2023-01-12
 * Time: 20:02
 */
public class Test2 {
}


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
//https://leetcode.cn/problems/construct-string-from-binary-tree/submissions/394858839/
    //迭代栈法题解
class Solution {
    public String tree2str(TreeNode root) {
        if (root == null) {//结点为空，不必返回()
            return "";
        }
        if (root.left == null && root.right == null) {//叶子节点只返回值
            return Integer.toString(root.val);
        }
        if (root.right == null) {//只有右为空，返回形式为root(root.left)
            return new StringBuilder().append(root.val).append("(").append(tree2str(root.left)).append(")").toString();
        }
        //剩余的就是左为任意，右不为空，返回形式为root.val(root.left)((root.right))
        return new StringBuilder().append(root.val).append("(").append(tree2str(root.left)).append(")(").append(tree2str(root.right)).append(")").toString();
    }
}